package com.seanbot.armstrong.rc4cipher;

import java.io.UnsupportedEncodingException;

public class CipherAlgorithm {
	String key;
	int k = 0;
	int l = 0;
	byte[] streamArray;
	

	public CipherAlgorithm(String key) throws UnsupportedEncodingException {
		this.key = key;
	}

	public void createStream() throws UnsupportedEncodingException {
		k = 0;
		l = 0;
		
		this.streamArray = new byte[256];
		for (int i = 0; i < 256; i++)
			streamArray[i] = (byte) i;
		byte[] keyArray = key.getBytes("UTF8");
		for (int i = 0, j = 0; i < 256; i++) {
			j = (j + streamArray[i] + keyArray[i % key.length()]) & 0xff;
			byte temp = streamArray[i];
			streamArray[i] = streamArray[j];
			streamArray[j] = temp;
		}
	}

	public String getStreamNext() throws UnsupportedEncodingException {

		byte byt;

		k = (k + 1) & 0xff;
		l = (l + streamArray[k]) & 0xff;
		
		//swap streamArray[k] with [l]
		byte temp = streamArray[k];
		streamArray[k] = streamArray[l];
		streamArray[l] = temp;
		
		//set byt to the stream @ pos i, convert to hexString and return it
		byt = streamArray[(streamArray[k] + streamArray[l]) & 0xff];

		return String.format("%02x", byt);
	}
}
